<template>
	<section id="market">

		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--价格列表-->
		<el-table
				:data="marketList.filter(data => !search || data.typeName.toLowerCase().includes(search.toLowerCase()))"
				border
				style="width: 100%;"
				v-loading="listLoading"
		>
			<el-table-column prop="accountName" label="账号" min-width="120" sortable>
			</el-table-column>
			<el-table-column prop="typeName" label="猪" min-width="160" sortable>
			</el-table-column>
			<el-table-column prop="price" label="价格" min-width="160" sortable>
			</el-table-column>
			<el-table-column prop="days" label="天数" min-width="160" sortable>
			</el-table-column>
			<el-table-column label="盈利" min-width="160" sortable>
				<template slot-scope="scope">
					￥{{scope.row.price * scope.row.percent}}
				</template>
			</el-table-column>
			<el-table-column prop="nowTime" label="创建时间" min-width="160" sortable>
			</el-table-column>
			<el-table-column prop="endTime" label="结束" min-width="160" sortable>
			</el-table-column>
			<el-table-column label="倒计时" prop="djs" min-width="160" sortable>
				<!--<template slot-scope="scope">-->
					<!--{{}}-->
					<!--{{timeDown(scope.row.endTime)}}-->
				<!--</template>-->
			</el-table-column>
			<el-table-column label="操作" width="250">
				<template slot="header" slot-scope="scope">
					<el-input
							v-model="search"
							size="mini"
							placeholder="输入名字搜索"/>
				</template>
				<template slot-scope="scope">
					<!--<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>-->
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px"  ref="addForm">
				<el-form-item label="账号" prop="account">
					<el-cascader :props="{ checkStrictly: true }" :options="accountOptions" v-model="addForm.accountName" :show-all-levels="false"></el-cascader>
				</el-form-item>
				<el-form-item label="猪" prop="typeName">
					<el-select v-model="addForm.priceId" @change="selectChange" filterable placeholder="请选择">
						<el-option
								v-for="item in priceOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="价格" prop="price">
					<el-input-number v-model="addForm.price" :min="1" auto-complete="off"></el-input-number>
				</el-form-item>
				<el-form-item label="日期" prop="price">
					<el-date-picker
							v-model="addForm.nowTime"
							type="date"
							value-format="yyyy-MM-dd"
							placeholder="选择日期">
					</el-date-picker>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import { selectFormat } from "@/libs/format";
	import {getAccountList} from "../../api/account/api";
	import {getPriceList} from "../../api/price/api";
	import {addMarket,getMarketList} from "../../api/market/api";
	import moment from 'moment'
	export default {
		data() {
			return {
				time : '',
				startTime:'',
				flag : false,
				addFormVisible:false,
				addLoading:false,
				search:'',
				marketList: [],  //待出售列表
				accountOptions:[], // 用户下拉列表
				priceList:[],  //   价格列表
				priceOptions:[],  // 价格下拉列表
				listLoading: false,
				addForm: {
					priceId:'',
					accountName: '',
					typeName: '', //猪名字
					days: '', //天数
					percent: '', // 百分比
					price: '', // 价格
					nowTime: moment().format('YYYY-MM-DD'), // 日期
					userId: JSON.parse(sessionStorage.getItem('user'))._id
				},
				notifyPromise:Promise.resolve()
			}
		},
		watch: {

			marketList:{
				handler:function(val,oldval){
					val.forEach(item=>{
						console.log(item.showTip)
						if(item.showTip){
							let msg = '账号'+item.accountName + '的'+ item.typeName + '猪该卖了'
							this.notify(msg);
						}
					})
				},
				deep:true//对象内部的属性监听，也叫深度监听

			}
		},
		methods: {
			notify(msg) {
				this.notifyPromise = this.notifyPromise.then(this.$nextTick).then(()=>{
					this.$notify({
						title: "警告",
						type: 'warning',
						message: msg,
						dangerouslyUseHTMLString: true,
						duration: 0,
					});
				})
			},
			// 价格选择
			selectChange(value){
				let id = value
				let obj = this.priceList.find(item=>{
					return id == item._id
				})
				this.addForm.typeName = obj.typeName
				this.addForm.percent = obj.percent
				this.addForm.days = obj.days
				this.startTime = obj.startTime
			},
			getPrice(){
				getPriceList({}).then((res) => {
					if(res.code == 200) {
						this.priceList = res.data
						const map = {
							label: 'typeName',
							value: '_id'
						}
						this.priceOptions = selectFormat.coverTree(res.data, map)
					}
				});
			},
			//获取用户列表
			getAccount() {
				let t = moment().format('YYYY-MM-DD');
				let tsub = moment(t, 'YYYY-MM-DD').add(10, 'days').format('YYYY-MM-DD');
				console.log(tsub);
				let para = {
					userId: JSON.parse(sessionStorage.getItem('user'))._id
				};
				getAccountList(para).then((res) => {
					const map = {
						label: 'accountName',
						value: 'accountName',
						children: 'children'
					}
					this.accountOptions = selectFormat.coverTree(res.data, map)
				});
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
			},
			// 查询待出售列表
			getMarket(){
				let para = {
					userId: JSON.parse(sessionStorage.getItem('user'))._id
				};
				getMarketList(para).then((res) => {
					if(res.code == 200){
						this.marketList = res.data
						this.marketList.forEach(item=>{
							item.showTip = false
							item.endTime = moment(item.nowTime, 'YYYY-MM-DD HH:mm').add(item.days, 'days').format('YYYY-MM-DD HH:mm');
							this.$set(
									item,"djs",this.timeDown(item.endTime)
							);
						})
					}
				});
			},
			// 添加
			addSubmit(){
				this.$confirm('确认提交吗？', '提示', {}).then(() => {
					if(this.addForm.nowTime){
						this.addForm.nowTime = this.addForm.nowTime + ' ' + this.startTime
					}
					if(this.addForm.accountName[this.addForm.accountName.length - 1]){
						this.addForm.accountName = this.addForm.accountName[this.addForm.accountName.length - 1]
					}
					if(!this.addForm.userId){
						this.$message.error('请刷新重试！	')
						return false
					}
					if(!this.addForm.accountName){
						this.$message.error('请选择账号');
						return false
					}
					if(!this.addForm.typeName){
						this.$message.error('请选择猪');
						return false
					}
					let para = Object.assign({}, this.addForm);
					addMarket(para).then((res) => {
						if(res.code == 200) {
							this.addFormVisible = false;
							this.getMarket()
						}
					});
				});
			},
			timeDown (endTime) {
				const end = new Date(endTime)
				const nowTime = new Date();
				let leftTime = parseInt((end.getTime()-nowTime.getTime())/1000)
				let d = parseInt(leftTime/(24*60*60))
				let h = this.forMate(parseInt(leftTime/(60*60)%24))
				let m = this.forMate(parseInt(leftTime/60%60))
				let s = this.forMate(parseInt(leftTime%60))
				if(leftTime <= 0){
					this.flag = true
				}
				return `${d}天${h}小时${m}分${s}秒`
			},
			forMate (time) {
				if(time>=10){
					return time
				}else{
					return `0${time}`
				}
			}
		},
		mounted() {
			this.getAccount()
			this.getPrice()
			this.getMarket()
			setInterval(()=> {
				for (let key in this.marketList) {
					const end = new Date(this.marketList[key]['endTime'])
					const nowTime = new Date();
					let leftTime = parseInt((end.getTime()-nowTime.getTime())/1000)
					let d = parseInt(leftTime/(24*60*60))
					let h = this.forMate(parseInt(leftTime/(60*60)%24))
					let m = this.forMate(parseInt(leftTime/60%60))
					let s = this.forMate(parseInt(leftTime%60))
					this.marketList[key].djs = `${d}天${h}小时${m}分${s}秒`;
					if(this.marketList[key].djs == '0天0小时0分0秒'){
						this.marketList[key].showTip = true
					}

				}
			}, 1000);
		}
	}

</script>

<style>
</style>
